<template>
    <div class="RealTimeObservation">
        <div class="top">
            <div class="top-left">
                <!-- <img src="../../../assets/bird.png" alt=""> -->
                <!-- <img :src="videoImage" alt=""> -->
                <div v-show="!loadSuccessful" style="width:100%;height: 100%;background:rgb(118 184 201 / 38%);text-align: center;line-height:5rem;border: 1px #67a4ab solid;font-size: 48px;">
                    <i class="el-icon-loading"></i>
                </div>
                <div v-show="loadSuccessful" style="width: 100%;height: 100%;position:relative;">
                    <video v-show="!isIdentify" ref="videoPlayer" class="video-js vjs-default-skin vjs-big-play-centered videoDemo" controls></video>
                    <img v-show="isIdentify" :src="videoImage" alt="">
                    <el-button style="position: absolute;right: 0px;bottom: 0px;" @click="btnStartIdentify()" class="sysButton">{{btnIdentifyText}}</el-button>
                </div>
            </div>
            <div class="top-center">
                <div class="titleP">
                    <p class="name">{{ deviceInfo.monitorPointName }}【{{deviceInfo.birdName}}】 </p>
                </div>
                <div class="banner">
                    <img src="../../../assets/banner.png" alt="" />
                </div>
                <div class="bottomList">
                    <div class="item">
                        <p>
                            <img :src="require(`@assets/monitor/s1.png`)" alt="" />
                        </p>
                        <p> <span>{{ currentWeight }}</span> <span class="unit">g</span> </p>
                        <p>重量</p>
                        <p class="activeTime">{{currentActiveTime}}</p>
                    </div>
                    <div class="item">
                        <p>
                            <img :src="require(`@assets/monitor/s2.png`)" alt="" />
                        </p>
                        <p> <span>{{currentBodyLength}}</span> <span class="unit">cm</span> </p>
                        <p>体长</p>
                        <p class="activeTime">{{currentActiveTime}}</p>
                    </div>
                    <div class="item">
                        <p>
                            <img :src="require(`@assets/monitor/s3.png`)" alt="" />
                        </p>
                        <p> <span>{{currentTemperature}}</span> <span class="unit">℃</span> </p>
                        <p>温度</p>
                        <p class="activeTime">{{currentActiveTime}}</p>
                    </div>
                    <div class="item">
                        <p>
                            <img :src="require(`@assets/monitor/s4.png`)" alt="" />
                        </p>
                        <p> <span>{{currentHumidness}}</span> <span class="unit">%</span> </p>
                        <p>湿度</p>
                        <p class="activeTime">{{currentActiveTime}}</p>
                    </div>
                </div>
            </div>
            <div class="top-right">
                <el-calendar v-model="timeValue" @input="calendarChange"></el-calendar>
            </div>
        </div>
        <div class="fourth">
          <SubTitle subTitle="照片"></SubTitle>
          <ul class="uList">
            <li v-for="(item, index) in imageList" :key="index" @click="showPop(item,true)">
              <img :src="`${$imageServer}${item.imageUrl}`" alt="" />
              <p class="opcityTime">{{ item.dateTime }}</p>
            </li>
          </ul>
          <Pagination  :total="page1.total" :currentPage="page1.currentPage" :pageSize="page1.pageSize" @handleCurrentChange="handleCurrentChange1" />
        </div>

        <div class="fifth">
          <SubTitle subTitle="视频"></SubTitle>
          <ul class="uList">
            <li v-for="(item, index) in videoList" :key="index" @click="showPop(item,false)">
              <video  alt="" >
                <source :src="`${$imageServer}${item.imageUrl}`" type="video/mp4">
              </video>
            </li>
          </ul>
          <Pagination  :total="page2.total" :currentPage="page2.currentPage" :pageSize="page2.pageSize" @handleCurrentChange="handleCurrentChange2" />
        </div>

    </div>
</template>

<script>

import flvjs from 'flv.js';

import SubTitle from "@/components/commons/SubTitle.vue";
import Charts from "@/components/commons/Charts.vue";
import Pagination from "@/components/commons/Pagination.vue";

import { loadVideo,closeVideo, getActivePage,startIdentify,closeIdentify ,getLastActive} from '../../../api/index';

export default {
    name: 'RealTimeObservation',
    props:['basePosition',"deviceInfo"],
    components: {
        SubTitle,
        Charts,
        Pagination
    },
    data() {
        return {
            currentWeight:0,
            currentBodyLength:0,
            currentHumidness:0,
            currentTemperature:0,
            currentActiveTime:null,
            timeValue: new Date(),
            page1 : {
              currentPage: 1,
              pageSize:10 ,
              total: 1000
            },
            page2 : {
              currentPage: 1,
              pageSize:10 ,
              total: 1000
            },
            imageList:[],
            videoList:[],
            videoImage:require('../../../assets/bird.png'),
            flvPlayer:null,
            videoUrl:null,
            loadSuccessful:false,
            btnIdentifyText:'开始识别',
            isIdentify:false,
            websocket:null
        }
    },
    created() {
        // getBirdsActivity().then(res=>{
        //     console.log(res)
        //     }
        // );
        this.initImage(this.timeValue,1);
        this.initVideo(this.timeValue,1);
        this.initLast();
    },
    methods: {
      
      handleCurrentChange1(val){
        // 修改页码
        this.page1.currentPage = val ;
        this.initImage(date,this.page1.currentPage);
      } ,
      handleCurrentChange2(val){
        this.page2.currentPage = val
        this.initVideo(date,this.page2.currentPage);
      },
      calendarChange(date){
        console.log(date);
        this.initImage(date,1);
        this.initVideo(date,1);
      },
      createVideo(url){
        if (flvjs.isSupported()) {
            var self = this;
            const videoElement = this.$refs.videoPlayer;
            this.flvPlayer = flvjs.createPlayer(
            {
                type: 'flv',
                // isLive: false,
                // hasAudio: false,
                url: url
            },
            {
                cors: true, // 是否跨域
                // enableWorker: true, // 是否多线程工作
                enableStashBuffer: false, // 是否启用缓存
                // stashInitialSize: 128, // 缓存大小(kb)  默认384kb
                autoCleanupSourceBuffer: true, // 是否自动清理缓存
                fixAudioTimestampGap: false //false才会音视频同步
            }
            );
            this.flvPlayer.attachMediaElement(videoElement);
            // 报错重连
            this.flvPlayer.on(flvjs.Events.ERROR, (errType, errDetail) => {
                console.log('errorType:', errType);
                console.log('errorDetail:', errDetail);
                // this.getVideo()
                
            });
            this.flvPlayer.on(flvjs.Events.LOADING_COMPLETE,(res)=>{
                // console.log(res);
            });
            this.flvPlayer.on(flvjs.Events.METADATA_ARRIVED,(res)=>{
                // console.log(res);
                self.loadSuccessful = true;
            });
            this.flvPlayer.load();
            this.flvPlayer.play();
        }
      },
      destoryVideo() {
        if(this.flvPlayer){
            this.flvPlayer.pause();
            this.flvPlayer.unload();
            this.flvPlayer.detachMediaElement();
            this.flvPlayer.destroy();
            this.flvPlayer = null;
            closeVideo({ videonumber: "0012" }).then(res=>{
                if(res.status != 200){
                    this.$message.error(res.data.data);
                    return;
                }
                console.log('成功关闭视频');
            });
        }
    },
      getVideo(){
        this.loadSuccessful = false;
        // 初始化
        loadVideo({ videonumber: "0012" }).then(res=>{
            //debugger;
            console.log(res)
            if(res.status != 200){
                this.$message.error(res.data.data);
            }
            if (this.flvPlayer) {
                this.destoryVideo();
            }
            this.createVideo(res.data.data);
        })
      },
      initImage(date,page){
        var currentDate = this.convertDateToStr(date);
        var self = this;
        getActivePage({currentPage:page,pageSize:10,filter:{id:this.deviceInfo.umID,suffix:'image',startTime:`${currentDate} 00:00:00`,endTime:`${currentDate} 23:59:59`}}).then(res=>{
            console.log(res)
            if(res.status != 200){
                this.$message.error(res.data.data);
                return;
            }
            self.page1.currentPage = res.data.page;
            self.page1.total = res.data.total;
            self.page1.pageSize = res.data.limit;
            self.imageList = res.data.data;

        }).catch(ex=>{
            this.$message.error(ex);
        });
      },
      initVideo(date,page){
        var currentDate = this.convertDateToStr(date);
        var self = this;
        getActivePage({currentPage:page,pageSize:10,filter:{id:this.deviceInfo.umID,suffix:'video',startTime:`${currentDate} 00:00:00`,endTime:`${currentDate} 23:59:59`}}).then(res=>{
            console.log(res)
            if(res.status != 200){
                this.$message.error(res.data.data);
                return;
            }
            self.page2.currentPage = res.data.page;
            self.page2.total = res.data.total;
            self.page2.pageSize = res.data.limit;
            self.videoList = res.data.data;

        }).catch(ex=>{
            this.$message.error(ex);
        });
      },
       showPop(item,isImg){
        window.MonitoringDynamics && window.MonitoringDynamics.setPopData(item,isImg)
      },
      btnStartIdentify(){
        console.log(this.isIdentify);
        if(this.isIdentify){
            this.getVideo();
            this.btnIdentifyText='开始识别';
            this.isIdentify = false;
        }else{
            this.btnIdentifyText='停止识别';
            this.destoryVideo();
            this.destoryWebSocket();
            startIdentify({ videonumber: "0012" }).then(res=>{
                console.log(res)
                if(res.status != 200){
                    this.$message.error(res.data.data);
                }
                this.startWebSocket(res.data.data);
            })
            this.isIdentify = true;
        }
      },
      startWebSocket(url){
      debugger;
      console.log(url);
        this.websocket = new WebSocket(url);
        this.websocket.onopen = this.onWebSocketOpen;
        this.websocket.onmessage =this.onWebSocketMessage;
        this.websocket.onclose=this.onWebSocketClose;
      },
      destoryWebSocket(){
        if(this.websocket!=null){
            this.websocket.onclose();
            closeIdentify({ videonumber: "0012" }).then(res=>{
                if(res.status != 200){
                    this.$message.error(res.data.data);
                    return;
                }
                console.log('成功关闭视频');
            });
        }
      },
      onWebSocketOpen(evt){
        console.log("连接成功");
      },
      onWebSocketMessage(evt){
        var data = JSON.parse(evt.data);
        if (data && data.type === 'image') {
            //var binaryData = new Uint8Array(data.image);
            //var blob = new Blob([binaryData], { type: 'image/jpeg' });
            //var url = URL.createObjectURL(blob);
            this.videoImage = "data:image/jpeg;base64," + data.image;
        }
      },
      onWebSocketClose(evt){

      },
      initLast(){
        debugger;
        getLastActive({ monitoringPointId: this.deviceInfo.umID }).then(res=>{
                if(res.status != 200){
                    this.$message.error(res.data.data);
                    return;
                }
                console.log(res)
                this.currentActiveTime = res.data.data.dateTime;
                this.currentBodyLength = res.data.data.bodyLength;
                this.currentHumidness = res.data.data.humidness;
                this.currentTemperature = res.data.data.temperature;
                this.currentWeight = res.data.data.weight;
            });
      },
      convertDateToStr(date){
        let year = date.getFullYear();
        let month =  (date.getMonth()+1).toString().padStart(2,'0');
        let day =  (date.getDate()).toString().padStart(2,'0');
        return `${year}-${month}-${day}`;
      }
    },
    mounted() {
        setTimeout(() => {
            this.getVideo()
        }, 300);
    },
    beforeDestroy(){
       this.destoryVideo();

       if(this.websocket){
            this.websocket.onclose();
        }
    }
}
</script>

<style lang="scss" scoped>
.RealTimeObservation {
    height: 100%;
    width: calc(100% - 44px);

    .sysButton {
        width: 98px;
        height: 32px;
        background: #73fff74d;
        display: flex;
        justify-content: center;
        align-items: center;
        border: 1px solid;
        border-image: linear-gradient(216deg, rgba(178, 255, 181, 0) 16%, rgba(178, 255, 181, 0.27) 78%) 1;
        color: #fff;
    }

    .top {
        display: flex;
        justify-content: space-between;
        width: 100%;
        height: 500px;
        background: linear-gradient(90deg, rgba(25, 99, 135, 0.25) 0%, rgba(25, 99, 135, 0.35) 100%);
        padding: 10px;
        .top-left {
            width: 40%;
            display: flex;
            align-items: center;
            img {
                width: 100%;
                height: 100%;
            }
            video {
                width: 100%;
                height: 100%;
            }
        }

        .top-center {
            margin: 0 10px;
            width: 400px ;
            display: flex;
            flex-direction: column;
            align-items: center;
            .titleP {
                margin-top: 20px;

                text-align: center;
                .name {
                    font-family: PangMenZhengDao;
                    font-size: 36px;
                    letter-spacing: 0.2em;
                }


            }
            .banner {
                text-align: center;
                img {
                    width: 80%;
                }
            }
            .bottomList {
                display: flex;
                justify-content: space-between;
                width: 100%;
                >div {
                    width: 95px;
                    height: 125px;
                    padding: 6px 0px ;
                    border-radius: 6px;
                    background: rgba(25, 99, 135, 0.3);
                    backdrop-filter: blur(10px);
                    text-align: center;
                    
                    p:nth-of-type(1) {
                        img {
                            width: 20px;
                            margin-right: 10px;
                        }
                    }
                    p:nth-of-type(2) {
                        font-family: Source Han Sans;
                        font-size: 20px;
                        font-weight: bold;
                        .unit {
                            margin-left: 6px;
                            font-weight: normal;
                            font-size: 10px;
                            color: rgba(255, 255, 255, 0.5);
                        }
                    }

                    p:nth-of-type(3) {
                        margin-top: 8px;
                        font-family: Source Han Sans;
                        font-size: 10px;
                        color: rgba(255, 255, 255, 0.5);
                    }
                    p:nth-of-type(4) {
                        margin-top: 8px;
                        font-family: Source Han Sans;
                        font-size: 10px;
                        color: rgba(255, 255, 255, 0.5);
                    }
                }
            }
        }
        .top-right {
            margin-right: 40px;
            width: 400px;
            height: 200px;

        }
    }
    .second {
        margin-top: 20px;
        background: linear-gradient(90deg, rgba(25, 99, 135, 0.25) 0%, rgba(25, 99, 135, 0.35) 100%);
        height: 150px;
    }
    .third {
      margin-top: 20px;
      padding: 20px;
      background: linear-gradient(90deg, rgba(25, 99, 135, 0.25) 0%, rgba(25, 99, 135, 0.35) 100%);
      height: 280px;
      .chart-box {
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: space-between;
      }
    }
    .fourth {
        margin-top: 20px;
        height: 550px;
        padding: 20px;
        background: linear-gradient(90deg, rgba(25, 99, 135, 0.25) 0%, rgba(25, 99, 135, 0.35) 100%);
        .uList {
            display: flex;
           
            width: 100%;
            justify-content: space-between;
            flex-wrap: wrap;
            margin-top: 20px;
            li {
                width: 18%;
                position: relative;
                margin-bottom: 10px;
                img {
                    width: 100%;
                    object-fit: cover;
                    max-height: 1.8rem;
                }
                .opcityTime {
                    position: absolute;
                    bottom: 0;
                    left: 0;
                    width: 100%;
                    height: 20px;
                    line-height: 20px;
                    background: rgba(0, 0, 0, 0.5);
                }
            }
        }
    }
    .fifth {
        margin-top: 20px;
        height: 550px;
        padding: 20px;
        background: linear-gradient(90deg, rgba(25, 99, 135, 0.25) 0%, rgba(25, 99, 135, 0.35) 100%);
        .uList {
            display: flex;
            width: 100%;
            justify-content: space-between;
            flex-wrap: wrap;
            margin-top: 20px;
            li {
                width: 18%;
                video {
                    width: 100%;
                }
            }
        }
    }


}
::v-deep .el-calendar {
    background: transparent;
    width: 400px;
    .el-calendar-day {
        height: 0.55rem;
        width: 0.55rem;
        padding: 0;
        margin: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        border: none;
        font-size: 16px;
        span {
            display: block !important;
        }
    }


    .el-calendar__title {
        font-size: 20px;
        color: #fff;
    }
    .el-calendar-table td  {
        border: none;
    }
    .el-calendar-table .el-calendar-day:hover {
        background: none;
    }
    .current   {
        border: none;
        background: none;
    }
    .el-button {
        background: transparent;
        outline: none;
        border: none;
        color: #fff;
    }
    .el-calendar__body th {
        color: #fff;
    }
    .is-selected {
        width: 0.55rem;
        height: 0.55rem;

        span {
            background: rgba(178, 255, 181, 0.76) !important;
            width: 0.3rem;
            height: 0.3rem;
            text-align: center;
            line-height: 0.3rem;
            border-radius: 50%;
        }
        border-radius: 50% ;
        color: #fff;
    }
    .is-today {
        color: #fff;
    }
}
</style>